package com.regulareport.web.controller.report;

import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.regulareport.form.domain.ReportVerificationResult;
import com.regulareport.form.domain.ReportVerifyReq;
import com.regulareport.form.domain.excel.ReportVerificationResultExcel;
import com.regulareport.form.service.IReportVerificationConfigService;
import com.regulareport.form.service.IReportVerificationResultService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.regulareport.common.annotation.Log;
import com.regulareport.common.core.controller.BaseController;
import com.regulareport.common.core.domain.AjaxResult;
import com.regulareport.common.enums.BusinessType;
import com.regulareport.common.utils.poi.ExcelUtil;
import com.regulareport.common.core.page.TableDataInfo;

/**
 * 校验结果Controller
 * 
 * @author
 * @date 2025-10-08
 */
@RestController
@RequestMapping("/report/verify/result")
public class ReportVerificationResultController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(ReportVerificationResultController.class);
    @Autowired
    private IReportVerificationResultService reportVerificationResultService;

    @Autowired
    private IReportVerificationConfigService reportVerificationConfigService;

    /**
     * 查询校验结果列表
     */
    @PreAuthorize("@ss.hasPermi('system:result:list')")
    @GetMapping("/list")
    public TableDataInfo list(ReportVerificationResult reportVerificationResult)
    {
        startPage();
        List<ReportVerificationResult> list = reportVerificationResultService.selectReportVerificationResultList(reportVerificationResult);
        return getDataTable(list);
    }

    /**
     * 导出校验结果列表
     */
    @PreAuthorize("@ss.hasPermi('system:result:export')")
    @Log(title = "校验结果", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ReportVerificationResult reportVerificationResult)
    {
        List<ReportVerificationResult> list = reportVerificationResultService.selectReportVerificationResultList(reportVerificationResult);
        ExcelUtil<ReportVerificationResult> util = new ExcelUtil<ReportVerificationResult>(ReportVerificationResult.class);
        util.exportExcel(response, list, "校验结果数据");
    }

    @PreAuthorize("@ss.hasPermi('report:verify:export')")
    @Log(title = "校验结果批量导出", businessType = BusinessType.EXPORT)
    @PostMapping("/multi/export")
    public void multiExport(HttpServletResponse response, @RequestBody ReportVerifyReq req)
    {
        log.info("校验结果批量导出方法开始-----------------------------请求参数： {} ",  req.getTaskIds());
        ExcelWriter excelWriter = null;
        try {
            Map<String, List<ReportVerificationResultExcel>> resultMap = reportVerificationResultService.selectReportVerificationResultMap(req.getTaskIds());
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("多Sheet导出示例", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 获取输出流
            excelWriter = EasyExcel.write(response.getOutputStream()).build();

//          excelWriter = EasyExcel.write(reportTaskList.get(0).getDataDate() + "校验结果.xlsx").build();
            AtomicInteger sheetInt = new AtomicInteger(0);
            Iterator<Map.Entry<String, List<ReportVerificationResultExcel>>> iterator = resultMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, List<ReportVerificationResultExcel>> entry = iterator.next();
                //创建sheet
                WriteSheet verificationResultSheet = EasyExcel.writerSheet(sheetInt.get(), entry.getKey())
                        .head(ReportVerificationResultExcel.class)
                        .build();

                // 写入数据到Sheet
                excelWriter.write(entry.getValue(), verificationResultSheet);
                sheetInt.getAndIncrement();
            }

            System.out.println("多Sheet导出完成，文件路径：" + "fileName");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("校验结果批量导出出错--------------------{}", e.getMessage());
            AjaxResult.error(e.getMessage());
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }


    /**
     * 获取校验结果详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:result:query')")
    @GetMapping(value = "/{pkId}")
    public AjaxResult getInfo(@PathVariable("pkId") Long pkId)
    {
        return success(reportVerificationResultService.selectReportVerificationResultByPkId(pkId, 0L));
    }

    /**
     * 校验
     */
    @PreAuthorize("@ss.hasPermi('system:result:query')")
    @Log(title = "校验结果", businessType = BusinessType.INSERT)
    @PostMapping(value = "/process")
    public AjaxResult reportVerificationExecute(@RequestBody ReportVerifyReq req)
    {
        log.info("校验方法开始-----------------------------请求参数： {} ",  req.getTaskIds());
////        ReportVerificationResult reportVerificationResult = new ReportVerificationResult();
//        String reportFormIds = String.valueOf(reportFormMap.get("reportFormIds"));
        return success(reportVerificationResultService.processReportVerificationResult(req.getTaskIds()));
    }

    /**
     * 修改校验结果
     */
    @PreAuthorize("@ss.hasPermi('system:result:edit')")
    @Log(title = "校验结果", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ReportVerificationResult reportVerificationResult)
    {
        return toAjax(reportVerificationResultService.updateReportVerificationResult(reportVerificationResult));
    }

    /**
     * 删除校验结果
     */
    @PreAuthorize("@ss.hasPermi('system:result:remove')")
    @Log(title = "校验结果", businessType = BusinessType.DELETE)
	@DeleteMapping("/{pkIds}")
    public AjaxResult remove(@PathVariable Long[] pkIds)
    {
        return toAjax(reportVerificationResultService.deleteReportVerificationResultByPkIds(pkIds));
    }

}
